package juc.blockqueue.arrayblockqueue;

/**
 * @ClassName TaskDispatcher
 * @PackageName juc.blockqueue.arrayblockqueue
 * @projectName myThread
 * @Description 
 * @Author games
 * @Date 2025/9/4 上午10:37
 * @Version 1.0
 */
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class TaskDispatcher {
    /**
     * 主方法：演示一个简单的任务生产者-消费者模型
     * 使用阻塞队列(ArrayBlockingQueue)来管理任务
     * 创建一个任务生产者和多个工作线程来模拟线程池
     * 3. 任务分发场景
     * @param args 命令行参数（未使用）
     */

    public static void main(String[] args) {
        // 任务队列
        BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<>(10);

        // 任务生产者
        Thread taskProducer = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                final int taskId = i;
                Runnable task = () -> {
                    System.out.println("Executing task " + taskId
                            + " by " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000); // 模拟任务执行
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    System.out.println("Task " + taskId + " completed");
                };

                try {
                    taskQueue.put(task);
                    System.out.println("Task " + taskId + " added to queue");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        // 工作线程池
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                try {
                    while (true) {
                        Runnable task = taskQueue.take(); // 获取任务
                        task.run(); // 执行任务
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }, "Worker-" + i).start();
        }

        taskProducer.start();
    }
}
